package com.cssy.yd.logic.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cssy.authority.service.IScDepartmentService;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.service.IBasicCompanyService;


import com.cssy.yd.logic.entity.LogicPoWareDO;
import com.cssy.yd.logic.entity.LogicPoWareItemDO;
import com.cssy.yd.logic.entity.LogicSoWareItemBatchDO;
import com.cssy.yd.logic.entity.LogicSoWareItemDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezeDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezeItemDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezedealDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezedealItemBatchDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezedealItemDO;

import com.cssy.yd.logic.service.ILogicSoItemService;

import com.cssy.yd.logic.service.ILogicSoService;
import com.cssy.yd.logic.service.ILogicSoWareItemService;
import com.cssy.yd.logic.service.ILogicSoWareService;
import com.cssy.yd.logic.service.ILogicSoWarefreezeService;
import com.cssy.yd.logic.service.ILogicSoWarefreezedealService;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;

/**
 * 销售冻结处理控制器
 * @author huang.xuming [2013-8-23]
 *
 */
@Controller
@RequestMapping("/yd/logic/sowarefreezedeal")
public class SoWareFreezeDealController extends BaseController<LogicSoWarefreezedealDO> {

	private static final Logger logger = Logger.getLogger(SoWareFreezeDealController.class);
			
	private static final String MANAGER = "/yd/logic/sowarefreezedeal/Manager";// 列表页面
	private static final String EIDT = "/yd/logic/sowarefreezedeal/Operation";// 添加、修改、显示页面
	private static final String ITEMMANGER = "/yd/logic/sowarefreezedeal/ItemManager";
	@Resource(name = "logicSoWareService")
	private ILogicSoWareService logicSoWareService;
	@Resource(name = "logicSoService")
	private ILogicSoService logicSoService;
	@Resource(name = "logicSoItemService")
	private ILogicSoItemService logicSoItemService;
	@Resource(name = "logicSoWareItemService")
	private ILogicSoWareItemService logicSoWareItemService;
	@Resource(name = "basicCompanyService")
	IBasicCompanyService basicCompanyService;
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	@Resource(name = "logicSoWarefreezeService")
	private ILogicSoWarefreezeService logicSoWarefreezeService;
	
	@Resource(name = "logicSoWarefreezedealService")
	private ILogicSoWarefreezedealService logicSoWarefreezedealService ;

	
	@Resource(name = "scDepartmentService")
    private IScDepartmentService scDepartmentService;
	
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}
	
	@RequestMapping("itemManager")
	public String itemManager(HttpServletRequest request, Model model)
			throws Exception {
		String itemdata =request.getParameter("data");
		String billstatus =request.getParameter("billstatus");
		String whcode =request.getParameter("whcode");
		LogicSoWarefreezedealItemDO soWareItemDO =JSONArray.parseObject(new String(itemdata.getBytes("ISO-8859-1"),"UTF-8"), LogicSoWarefreezedealItemDO.class);
		LogicSoWarefreezedealItemBatchDO sItemBatchDO = new LogicSoWarefreezedealItemBatchDO();
		if(soWareItemDO != null){
			sItemBatchDO.setMaterialsid(soWareItemDO.getMaterialsid());
			sItemBatchDO.setProdNo(soWareItemDO.getProdNo());
			sItemBatchDO.setProdName(soWareItemDO.getProdName());
			sItemBatchDO.setProdSpecDesc(soWareItemDO.getProdSpecDesc());
			sItemBatchDO.setProdBUnit(soWareItemDO.getProdBUnit());
			sItemBatchDO.setProdUnit(soWareItemDO.getProdUnit());
			sItemBatchDO.setProdUnitConvert(soWareItemDO.getProdUnitConvert());
			sItemBatchDO.setTmpCanFrozenQuantity(soWareItemDO.getTmpCanFrozenQuantity());
			sItemBatchDO.setStatus(soWareItemDO.getStatus());
			model.addAttribute("sItemBatchDO",JSONArray.toJSONString(sItemBatchDO));
			model.addAttribute("itemBatch",soWareItemDO.getItemBatch());
		}
		model.addAttribute("billstatus",billstatus);
		model.addAttribute("whcode",whcode);
		return ITEMMANGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		SearchResult result = logicSoWarefreezedealService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}
	@RequestMapping(value = "/itemlist")
	public void itemlist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String itembatch =request.getParameter("itembatch");
		List<LogicSoWarefreezedealItemBatchDO> itemBatchDOs=null;
		if(itembatch != null  && !"".equals(itembatch.trim())){
			itemBatchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicSoWarefreezedealItemBatchDO.class);
		}
		SearchResult result= new SearchResult();
		if(itemBatchDOs != null && itemBatchDOs.size() > 0){
			result.setRecordCount(itemBatchDOs.size());
			result.setResults(itemBatchDOs);
		}
		 OutJsonGrid out=new OutJsonGrid(result);
		 out.printJSon(response);
		
	}
	@Override
	public String operationForm(HttpServletRequest request, 
			@PathVariable String id,@PathVariable String flag, Model model) throws Exception {
		
		
		if (OperationFlag.ADD.equals(flag)) {
			// 新增加时操作
			model.addAttribute("flag", "ADD");
			
		} else {
			LogicSoWarefreezedealDO sowarefreeze = logicSoWarefreezedealService.findListById(id);
			//List<LogicSoWarefreezedealItemDO> sowareitem = logicSoWarefreezedealService.findItemListBysowfdId(sowarefreeze.getId());
			//TODO 获取订单相应出库、冻结信息
			model.addAttribute("flag", "EDIT");
			model.addAttribute("soware", sowarefreeze);
			//model.addAttribute("sowareitem", sowareitem);
		}
		
		
		//可冻结的冻结申请单
		SearchConditions scsso = new SearchConditions();
		scsso.addCondition("billstatus", "2", SearchCondition.OP_EQUAL);// 订单状态-二审完结、三审完结
		scsso.addCondition("frozen_status", "0,2", SearchCondition.OP_IN);// 冻结状态-未冻结、部分冻结
		scsso.setLimitPage(false);// 不分页
		@SuppressWarnings("unchecked")
		List<LogicSoWarefreezeDO> swflist = logicSoWarefreezeService.findListByExample(scsso).getResults();
		model.addAttribute("swflist", swflist);
		
		//仓库
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		
		//部门列表
		model.addAttribute("depts",SoController.getDepartmentList(scDepartmentService));
				
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicSoWarefreezedealDO sowarefreeze = logicSoWarefreezedealService.findListById(id);
			List<LogicSoWarefreezedealItemDO> sowareitem = logicSoWarefreezedealService.findItemListBysowfdId(sowarefreeze.getId());
			OutJsonGrid out = new OutJsonGrid(sowareitem);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicSoWarefreezedealDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		if(StringUtils.isBlank(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("物料内容不能为空！");
			return bodyMap.modelMap;
		}else{
			List<LogicSoWarefreezedealItemDO> soWarefreezedealItemDOs  = JSONArray.parseArray(itemdata, LogicSoWarefreezedealItemDO.class);
			for (LogicSoWarefreezedealItemDO sItemDO : soWarefreezedealItemDOs) {
				if("Y".equals(sItemDO.getOpenBatch())){
					if(sItemDO.getItemBatch() != null && !"".equals(sItemDO.getItemBatch())){
						List<LogicSoWarefreezedealItemBatchDO> batchDOs  = JSONArray.parseArray(sItemDO.getItemBatch(), LogicSoWarefreezedealItemBatchDO.class);
						if(batchDOs==null || batchDOs.size() <= 0){
							bodyMap.isFail();
							bodyMap.configWebInfor("物料编码为:'"+sItemDO.getProdNo()+"'没有分批次填写数据！");
							return bodyMap.modelMap;
						}
					}else{
						bodyMap.isFail();
						bodyMap.configWebInfor("物料编码为:'"+sItemDO.getProdNo()+"'没有分批次填写数据！");
						return bodyMap.modelMap;
					}
				}
			}
		}try {
			logicSoWarefreezedealService.sowfdSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicSoWarefreezedealDO ld = logicSoWarefreezedealService.findListById(field);
				ld.setRemoved(1);
				logicSoWarefreezedealService.update(ld,  SessionUtil.getUser(request));
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 根据冻结申请编号，获取销售冻结信息
	 * @param sowarefreezeNo
	 * @param request
	 * @param response
	 */
	@RequestMapping("/getSowarefreeze")
	public void getSowarefreeze(@RequestParam("sowarefreezeNo") String sowarefreezeNo, HttpServletRequest request, HttpServletResponse response){
		BodyMsg bodyMap = BodyMsg.getInstance();
		
		LogicSoWarefreezeDO soWarefreezeDO = null ;
		Map<String ,Object> map = new HashMap<String, Object>();
		
		SearchConditions scsso = new SearchConditions();
		scsso.addCondition("no", sowarefreezeNo, SearchCondition.OP_EQUAL);// 订单状态-二审完结、三审完结
		scsso.setLimitPage(false);// 不分页
		@SuppressWarnings("unchecked")
		List<LogicSoWarefreezeDO> swflist = logicSoWarefreezeService.findListByExample(scsso).getResults();
		if(null != swflist && swflist.size() > 0){
			soWarefreezeDO = swflist.get(0);
			map.put("bean", soWarefreezeDO);
		}else{
			logger.warn("swflist is null - "+sowarefreezeNo);
			bodyMap.isFail("找不到指定对象");
		}
		
		response.setContentType("text/text;charset=UTF-8");
		PrintWriter out=null;
		
		 try {
			 out=response.getWriter();
			 out.write(JSONObject.toJSONString(map));
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}finally{
			if(out!=null){
				out.flush();
				out.close();
			}
		}
		
	}
	
	/**
	 * 获取指定冻结申请单ID的item项
	 * @param sowarefreezeId
	 * @param request
	 * @param response
	 */
	@RequestMapping("/sowarefreezeitemlist")
	public void sowarefreezeitemlist(@RequestParam("sowarefreezeId") String sowarefreezeId, HttpServletRequest request, HttpServletResponse response){
		SearchResult result= new SearchResult();
		LogicSoWarefreezeItemDO bean = new LogicSoWarefreezeItemDO();
		
		List<LogicSoWarefreezeItemDO> soitemlist = new ArrayList<LogicSoWarefreezeItemDO>();
		if(StringUtils.isNotBlank(sowarefreezeId)){
			bean.setSoNo(sowarefreezeId);
			soitemlist = logicSoWarefreezeService.findItemListBysowarefreezeId(sowarefreezeId);
		}
		
		result.setResults(soitemlist);
		result.setRecordCount(soitemlist.size());
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}
	
	
	
	@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
//		try {
//			
//			
//			String id = request.getParameter("id");
//			LogicSoWareDO soware=new LogicSoWareDO();
//			List<LogicSoWareItemDO> lp=new ArrayList<LogicSoWareItemDO>();
//			List<LogicFreightageDO> freightageDOs=new ArrayList<LogicFreightageDO>();
//			if(!"".equals(id)&&id!=null){
//				soware = logicSoWareService.findListById(id);
//			}
//			if(soware.getId()!=null){
//				lp = logicSoWareItemService.findItemListBysowareId(soware.getId());
//				SearchConditions sc = new SearchConditions();
//				sc.setRemovedProperty(null);//判断是否有删除标识
//				sc.addCondition("tid", soware.getId(), SearchCondition.OP_EQUAL);
//				freightageDOs=logicFreightageService.findListByExample(sc).getResults();
//			}
//			if(lp.size()>0){
//				request.setAttribute("soware", soware);
//				request.setAttribute("lp", lp);
//				request.setAttribute("row", lp.size());
//				if(freightageDOs.size()>0){
//					for(int i=0;i<freightageDOs.size();i++){
//						if("铁运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("T", freightageDOs.get(i).getFreightageprice());
//						}
//						if("海运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("H", freightageDOs.get(i).getFreightageprice());
//						}
//						if("短运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("D", freightageDOs.get(i).getFreightageprice());
//						}
//						if("装卸费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("Z", freightageDOs.get(i).getFreightageprice());
//						}
//						if("落箱费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("L", freightageDOs.get(i).getFreightageprice());
//						}
//						if("其他".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("Q", freightageDOs.get(i).getFreightageprice());
//						}
//					}
//					
//				}
//				
//				response.setContentType("application/vnd.ms-excel");
//				response.setHeader("Content-disposition", "attachment;filename=export_" + System.currentTimeMillis() + ".xls");
//			
//				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/SoWarePrint.jsp");
//			
//				dispatcher.forward(request, response);
//			}
//		} catch (ServletException e) {
//			e.printStackTrace();
//		}
	}
	
}
